<?php

/**
 * Backhand script for uplading a Document
 * @package ModuleGestionDocuments
 * @version 1.0b
 */

session_start();

// Configuration file
include '../configuration.php';
// Functions
include '../inc/functions.php';

// Include all objects
// TODO: Include only needed classes
foreach (glob($configuration['webroot'].'objects/*.php') as $class) { include_once $class; }

if (!empty($_FILES) && !(empty($_POST['otype']) || empty($_POST['id']))) {

	try {
		// Creating Document object in database
		$document = new Document();
		$document->extension = substr(strrchr($_FILES['Filedata']['name'], '.'), 1);
		$document->filename = basename($_FILES['Filedata']['name'], '.'.$document->extension);
		$documentId = $document->SaveNew();
		
		// Generating associated object
		switch ($_POST['otype']) {
			case 'activity'			: $object = new Activity(); break;
			case 'contact'			: $object = new Contact(); break;
			case 'company'			: $object = new Company(); break;
			case 'gotprorole'		: $object = new GotProRole(); break;
			case 'studentactivity'	: $object = new GotStudentActivity(); break;
			case 'supportcase'		: $object = new SupportCase(); break;
			case 'update'			: $object = new Update(); break;
			default: break;
		}
		
		$object->Get($_POST['id']);
		$object->AddDocument($document);
		$object->Save();

		// Moving file to its location
		$targetPath = $_SERVER['DOCUMENT_ROOT'].$_REQUEST['folder'].'/';
		$targetFile = str_replace('//', '/', $targetPath).$documentId.'.'.$document->extension;
		
		move_uploaded_file($_FILES['Filedata']['tmp_name'], $targetFile);
		echo str_replace($_SERVER['DOCUMENT_ROOT'], '', $targetFile);
		
	} catch (Exception $e) {
		error_log($e->getMessage());
	}
}
?>